import React, { Component } from 'react';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { View, StyleSheet, FlatList, TouchableOpacity } from 'react-native';
import { Text, List, ListItem, Icon, Button } from 'react-native-elements';
import { primaryColor, calculateInsurancePrice } from '../utils'; 
import AddSubtractGroup from './AddSubtractGroup';

const styles = StyleSheet.create({
  header: {
    padding: 8
  },
  list: {
    flex: 1,
    marginTop: 0,
    backgroundColor: 'white'
  },
  subtitle: {
    paddingLeft: 10
  },
  description: {
    color: 'gray',
    fontSize: 12
  },
  buttonBar: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  subtotal: {
    color: 'gray'
  },
  price: {
    color: 'black'
  },
  row: {
    paddingLeft: 8,
    flexDirection: 'row',
    alignItems: 'center'
  },
  fill: {
    flex: 1
  },
  container: {
    flex: 1,
  },
  checkout: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: primaryColor,
    padding: 12
  },
  checkoutText: {
    color: 'white',
    fontSize: 16,
    textAlign: 'center'
  }
});

export default class ShoppingCart extends Component {
  componentWillReceiveProps(nextProps) {
    if (this.props.scrollToTop!==nextProps.scrollToTop) {
      this.refs.flatlist.scrollToOffset({index: 0});  
    }
  }
  onAddDry = (item) => {
    this.onUpdateItem({
      ...item,
      dryCount: (item.dryCount||0) + 1
    });
  }
  onSubtractDry = (item) => {
    this.onUpdateItem({
      ...item,
      dryCount: Math.max(0, (item.dryCount||0) - 1)
    });
  }
  onAddWash = (item) => {
    this.onUpdateItem({
      ...item,
      washCount: (item.washCount||0) + 1
    });
  }
  onSubtractWash = (item) => {
    this.onUpdateItem({
      ...item,
      washCount: Math.max(0, (item.washCount||0) - 1)
    });
  }
  onAddIron = (item) => {
    this.onUpdateItem({
      ...item,
      ironCount: (item.ironCount||0) + 1
    });
  }
  onSubtractIron = (item) => {
    this.onUpdateItem({
      ...item,
      ironCount: Math.max(0, (item.ironCount||0) - 1)
    });
  }
  onUpdateItem = (item) => {
    const index = this.props.selects.findIndex(node => node.id===item.id);
    this.props.onSelectUpdate([...this.props.selects.slice(0,index), item, ...this.props.selects.slice(index+1)]);
  }
  onRemoveItem = (item) => {
    const index = this.props.selects.findIndex(node => node.id===item.id);
    this.props.onSelectUpdate([...this.props.selects.slice(0,index), ...this.props.selects.slice(index+1)]);
  }
  onInsurance = (item) => {
    const navigation = this.props.navigation;
    navigation.navigate('Insurance', {item, onSelect: (insurance) => {
      setTimeout(() => {
        const index = this.props.selects.findIndex(node => node.id===item.id);
        this.props.onSelectUpdate([...this.props.selects.slice(0,index), {...item, insurance}, ...this.props.selects.slice(index+1)]);
      }, 300);
    }});
  }
  onAddLockerBag = () => {
    const navigation = this.props.navigation;
    navigation.navigate('LockerBag', {selectMode: true, onSelect: (arg, lockerBag) => {
      setTimeout(() => {
        const found = this.props.selects.find(item => item.id===lockerBag.id);
        if (!found) {
          this.props.onSelectUpdate([...this.props.selects, lockerBag]);
        }
      }, 300);
    }});
  }
  renderHeader = () => {
    const { chinese, selects, totalCount, totalPrice, valueForFree, deliveryFee, lockerBag } = this.props;
    return (
      <View>
        {lockerBag&&!selects.find(select => select.id===lockerBag.id)&&
          <ListItem title={chinese?'试试KnocKnocK锁包':'Try Our Locker Bag'} onPress={this.onAddLockerBag}
            subtitle={chinese?'节省您的时间':'Free your time'} leftIcon={{name:'fiber-new',color:primaryColor}}/>
        }
        <ListItem title={chinese?'衣物总价':'Subtotal'} subtitle={`${totalCount} ${chinese?'件':'items'}`}
          rightTitle={`$${totalPrice.toFixed(2)}`} rightTitleStyle={styles.price} hideChevron/>
        <ListItem rightTitle={`$${(valueForFree>0?deliveryFee:0).toFixed(2)}`} rightTitleStyle={styles.price}
          subtitle={(valueForFree>0)?`${chinese?'再添加':'Add'} $${valueForFree.toFixed(2)} ${chinese?'价值的衣物免递送费':'more value of items to get free delivery'}`:(chinese?'免费递送':'Free delivery')}
          title={chinese?'递送费':'Delivery fee'} hideChevron/>
      </View>
    );
  }
  renderItem = ({item}) => {
    const {chinese, type} = this.props;
    const {unit,imageUrl,name,dry,dryD,wash,washD,iron,ironD,dryDisplay,washDisplay,
      ironDisplay,dryCount=0,washCount=0,ironCount=0,insurance} = item;
    const totalCount = dryCount+washCount+ironCount;

    return (
      <ListItem roundAvatar avatar={{uri:imageUrl}} title={
        <View style={styles.row}>
          <Text style={styles.fill}>{name}</Text>
          {type==='premiumlaundry'&&<TouchableOpacity onPress={()=>this.onInsurance(item)}><Icon size={28} name='edit' color={primaryColor}/></TouchableOpacity>}
        </View>
      } hideChevron subtitle={
          <View style={styles.subtitle}>
            {dry>0&&<Text style={styles.description}>{`${dryDisplay} ($${dryD||dry})`}</Text>}
            {dry>0&&<AddSubtractGroup count={dryCount} unit={unit}
              onAdd={()=>this.onAddDry(item)} onSubtract={()=>this.onSubtractDry(item)}/>}
            {wash>0&&<Text style={styles.description}>{`${washDisplay} ($${washD||wash})`}</Text>}
            {wash>0&&<AddSubtractGroup count={washCount} unit={unit}
              onAdd={()=>this.onAddWash(item)} onSubtract={()=>this.onSubtractWash(item)}/>}
            {iron>0&&<Text style={styles.description}>{`${ironDisplay} ($${ironD||iron})`}</Text>}
            {iron>0&&<AddSubtractGroup count={ironCount} unit={unit}
              onAdd={()=>this.onAddIron(item)} onSubtract={()=>this.onSubtractIron(item)}/>}
            <View style={styles.buttonBar}>
              <View style={styles.fill}>
                {(totalCount>0)&&<Text style={styles.subtotal}>{`$${(dryCount*(dryD||dry)+washCount*(washD||wash)+ironCount*(ironD||iron)).toFixed(2)} (${dryCount+washCount+ironCount} items)`}</Text>}
                {(totalCount>0)&&(insurance>0)&&this.props.config&&<Text style={styles.subtotal}>{`${chinese?'单件价值':'Item value'}: $${insurance} (+ $${calculateInsurancePrice(item, this.props.config)} ${chinese?'附加费':'Extra charge'})`}</Text>}
              </View>
              <Icon name='delete-forever' color='gray' size={28} onPress={()=>this.onRemoveItem(item)}/>
            </View>
          </View>
        }/>
    );
  }
  renderFooter = () => {
    return <ListItem hideChevron subtitleStyle={styles.description}
      leftIcon={{name: 'edit', color: primaryColor}} subtitle={this.props.chinese?`昂贵衣物，点击改按钮请提前申报其价值`:`For luxury or expensive items, you can click on this button to declare the value of them!`}/>
  }
  keyExtractor = (item) => item.id
  render() {
    const { selects, chinese, config, defaultAddressm, type, totalCount, totalPrice,
      deliveryFee, valueForFree } = this.props;

    return (
      <View style={styles.container}>
        <List style={styles.list}>
          <FlatList ref='flatlist' extraData={{totalCount,totalPrice,deliveryFee,valueForFree}} data={selects} keyExtractor={this.keyExtractor}
            ListFooterComponent={type==='premiumlaundry'?this.renderFooter:null} renderItem={this.renderItem}
            ListHeaderComponent={this.renderHeader}/>
        </List>
        <TouchableOpacity onPress={this.props.onCheckout} style={styles.checkout}>
          <Icon color='white' name='check'/>
          <Text style={styles.checkoutText}>{chinese?'结算':'Check Out'}</Text>
        </TouchableOpacity>
      </View>
    );
  }
}



